﻿function ltrim( str ){
	return str.replace(/^\s+/g,"")
};

function rtrim( str ){
	return str.replace(/^\s+$/g,"")
};

function trim( str ){
	return ltrim(rtrim(str));
};

function empty( str ){
	return trim(str).length == 0;
};

function hasClass(ele,cls) {
  return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
};
 
function addClass(ele,cls) {
  if (!this.hasClass(ele,cls)) ele.className += " "+cls;
};
 
function removeClass(ele,cls) {
  if (hasClass(ele,cls)) {
          var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
    ele.className=ele.className.replace(reg,' ');
  }
};

function contains( parent,child ){
	if(!child || !parent || child == parent ){
		return false;
	}
	while( child.nodeName != "BODY" && child != parent ){
		child = child.parentNode;
	}
	if(child==parent){
		return true;
	}
	return false;
};

String.prototype.endsWith = function( obj ) {
	var type = toString.call( obj );
	if(type == "[object Array]"){
		for(var i=0,l=obj.length;i<l;i++){
			if(this.match(new RegExp(obj[i]+"$","i"))){
				return true;
			}
		}
		return false;
	}
	return (this.match(new RegExp(obj+"$","i")));
};


//
window.addEventListener("DOMContentLoaded",function(){
	//菜单按钮高亮
	var menuwrappers = document.getElementsByClassName("menuwrapper");
	for(var i=0,l=menuwrappers.length;i<l;i++){
		menuwrappers[i].onmouseover = function(e){
			addClass(this,'highlight');
		}
		menuwrappers[i].onmouseout = function(e){
			removeClass(this,'highlight');
		}
	}

	//菜单组高亮
	var menugroups = document.getElementsByClassName("menugroup");

	var menugroupsBlur = function(){
		for(var i=0,l=menugroups.length;i<l;i++){
			removeClass(menugroups[i].getElementsByClassName("menugrouptitle")[0],'highlight');
			removeClass(menugroups[i].getElementsByClassName("menugroupcontent")[0],'highlight');
		}
	}; 

	for(var i=0,l=menugroups.length;i<l;i++){
		menugroups[i].onmouseover = function(e){
			menugroupsBlur();
			addClass(this.getElementsByClassName("menugrouptitle")[0],'highlight');
			addClass(this.getElementsByClassName("menugroupcontent")[0],'highlight');
		}
		menugroups[i].onmouseout = function(e){
			var srcElement = e.target;
			if(srcElement.nodeName != 'DIV'){
				return;
			}
			if( contains( this,e.relatedTarget ) ){
				return;
			}
			removeClass(this.getElementsByClassName("menugrouptitle")[0],'highlight');
			removeClass(this.getElementsByClassName("menugroupcontent")[0],'highlight');
			if(this.onmouseleave){
				this.onmouseleave();
			}
		}
	};
	//

	//展开按钮组
	var expandmenus = document.getElementsByClassName("expandmenu");

	//关闭所有已打开的可扩展的菜单
	var collapseAllExpandedMenus = function(){
		for( var i=0,l=expandmenus.length;i<l;i++){
			if(expandmenus[i].expanded){
				expandmenus[i].collpase();
			}
		}
	};
	
	for( var i=0,l=expandmenus.length;i<l;i++){
		var menugrp = expandmenus[i].parentNode.parentNode;

		expandmenus[i].expanded = false;
		expandmenus[i].menugrpInitWidth = menugrp.clientWidth+"px";

		/*鼠标离开关闭可扩展菜单*/
		/*menugrp.onmouseleave = function(){
			var expandBtn = this.getElementsByClassName("expandmenu")[0];
			if(expandBtn.expanded){
				expandBtn.collpase();				
			}
		};*/

		expandmenus[i].expand = function(){
			var menugrptemp = this.parentNode.parentNode;
			menugrptemp.style.width = menugrptemp.getAttribute("data-expandTo");
			addClass(this.parentNode,"expanded");
			this.expanded = true;
		};

		expandmenus[i].collpase = function(){
			var menugrptemp = this.parentNode.parentNode;
			menugrptemp.style.width = this.menugrpInitWidth;
			removeClass(this.parentNode,"expanded");
			this.expanded = false;
		};
		
		/*menugrp.addEventListener("webkitTransitionEnd",function( e ){
			console.log('transition end');
			if( e.elapsedTime == 0.65 ){//宽度改变的Event
			}
		},true);*/

		/*expandmenus[i].onmouseover = function(){
			collapseAllExpandedMenus();
			if(!this.expanded){
				this.expand();				
			}
		};*/

		expandmenus[i].onclick = function(){
			var menugrptemp = this.parentNode.parentNode;
			if(!this.expanded){
				collapseAllExpandedMenus();
				this.expand();
			}else{
				this.collpase();
			}
		};
	}

	//表情
	var emotesBtn= document.getElementById("emotes"),
		emotesmenugroup = emotesBtn.parentNode.parentNode.parentNode;

	var emotesListCtrl = {};
    
    var showEmotesTimeout,//定时器
        showEmotesTimeoutWaitTime=600;//鼠标悬浮600毫秒后才展开表情菜单

	emotesListCtrl.collapsedWidth = emotesmenugroup.clientWidth;
	emotesListCtrl.expandedWidth = 300;
	emotesListCtrl.isVisible = false;
	emotesListCtrl.show = function(){
		emotesmenugroup.style.width = emotesListCtrl.expandedWidth + "px";
		this.isVisible = true;
	};

	emotesListCtrl.hide = function(){
		emotesmenugroup.style.width = emotesListCtrl.collapsedWidth + "px";
		this.isVisible = false;
	}

	emotesBtn.onmouseover = function( e ){
        if(!showEmotesTimeout){
               showEmotesTimeout = setTimeout(function(){
                     //重置定时器
                     clearTimeout(showEmotesTimeout);
                     showEmotesTimeout = null;
                     //
                     var isMouseStillOver = !!hasClass(emotesBtn.parentNode,"highlight");
                     if(!isMouseStillOver){//鼠标已离开，但是鼠标移动速度太快导致onmouseleave事件未正确触发，不做操作
                        return;
                     }
                     //
                	 collapseAllExpandedMenus();
		             if(!emotesListCtrl.isVisible){
		            	emotesListCtrl.show();
	            	}
             },showEmotesTimeoutWaitTime);
        }
	};

	emotesmenugroup.onmouseleave = function(){
        //鼠标离开,中断执行展开表情
        if(showEmotesTimeout){
            clearTimeout(showEmotesTimeout);
            showEmotesTimeout = null;
        }
        //鼠标离开表情栏自动隐藏
		if(emotesListCtrl.isVisible){
			emotesListCtrl.hide();
		}
	};
	
	//表情上翻下翻按钮
	var emoteslist = document.getElementById("emoteslist"),
		emotesup = document.getElementById("emotesup"),
		emotesdown = document.getElementById("emotesdown"); 

	var emoteslistTopOffset = 0;

	var emotescrolluptimer,emotescrolldowntimer;

	var clearemotescrolldowntimer = function(){
		if(emotescrolldowntimer){
				clearInterval(emotescrolldowntimer)
				emotescrolldowntimer = null;
		}
	};

	var clearemotescrolluptimer = function(){
		if(emotescrolluptimer){
				clearInterval(emotescrolluptimer);
				emotescrolluptimer = null;
		}
	};

	var clearemoteautoscroltimer = function(){
		clearemotescrolluptimer();
		clearemotescrolldowntimer();
			
	};

	var emotescrolldown = function( step ){
		step = step || 48;//默认滚一屏
		emoteslistTopOffset += step;
		emoteslistTopOffset = Math.min(0,emoteslistTopOffset);
		emoteslist.style.top = emoteslistTopOffset+"px";
	};


	var emotescrollup= function( step ){
		step = step || 48;//默认滚一屏
		emoteslistTopOffset -= step;
		emoteslistTopOffset = Math.max(-240,emoteslistTopOffset);
		emoteslist.style.top = emoteslistTopOffset+"px";
	};

	//点击一次滚一屏
	emotesdown.onclick = function(){
			clearemoteautoscroltimer();
			emotescrollup();
	};

	emotesup.onclick = function(){
			clearemoteautoscroltimer();
			emotescrolldown();
	};
	
	//悬浮滚半屏
	emotesdown.onmouseover = function(){
			clearemotescrolluptimer();
			if(!emotescrolldowntimer){
				emotescrolldowntimer = setInterval(function(){
				emotescrollup(24);
				},1000);//800毫秒卷动一次,动画完成需要600毫秒
			}
	};

	emotesdown.onmouseout = function(){
		clearemotescrolldowntimer();
	};

	emotesup.onmouseover = function(){
			clearemotescrolldowntimer();
			if(!emotescrolluptimer){
				emotescrolluptimer = setInterval(function(){
					emotescrolldown(24);
				},1000);//800毫秒卷动一次,动画完成需要600毫秒
			}
	};

	emotesup.onmouseout = function(){
		clearemotescrolluptimer();
	};

	/********************* 界面部分完毕 *********************/

	//主菜单按钮动作
	var mainMenus = document.getElementsByClassName("menu");

	for( var i = 0,l=mainMenus.length;i<l;i++ ){
		var mainmenu = mainMenus[i];
		mainmenu.onclick = function(){
			var actionname = this.className.substring(5);//start end 5-end
			performAction(actionname);
		}
	}
	//表情按钮动作
	var emoteMenus = document.getElementById("emoteslist").getElementsByTagName("a");
	for( var i = 0,l=emoteMenus.length;i<l;i++ ){
		var emotemenu = emoteMenus[i];
		emotemenu.onclick = function(){
			var emotename = this.getAttribute("title");
			performEmote(emotename);
		}
	}

	//加载框架
	var loading = document.getElementById("loader"),
		frame =  document.getElementById("mainFrame"),
		frameMask = document.getElementById("mainFrameMask");
	
	frame.onload = function(){
		loading.style.opacity = "0";
		frameMask.style.opacity = "0";
	};

	loading.addEventListener("webkitTransitionEnd",function( e ){
		if(this.style.opacity == 0){
			this.style.display = "none";
		}
	},false);

	frameMask.addEventListener("webkitTransitionEnd",function( e ){
		if(this.style.opacity == 0){
			this.style.display = "none";
		}
	},false);

	var loadFrame = function( frameurl,width,height){
		frameMask.style.display = "";
		frameMask.style.opacity = "100";
		loading.style.display = "";
		loading.style.opacity = "100";
		frame.src = frameurl;
		if(width){frame.width = width;}
		if(height){frame.height = height;}
		//鼠标在frame上取消菜单高亮
		frame.onmouseover = function(){
			menugroupsBlur();
            //表情菜单收起
            if(emotesListCtrl.isVisible){
			    emotesListCtrl.hide();
		    }
		}
	};

	//数据接收
	chrome.extension.onConnect.addListener(function(port){
		if(port.name != "quickshare"){ return; }
		port.onMessage.addListener(function(msg){
			handleMessage(msg);
		});
	});

	//数据处理handleMessage
	var handleMessage = function( msg ){
		//console.log('recieved msg');
		//console.log(msg);
		if("onClickData" in msg){
			handleMessage.data.onClickData = msg.onClickData;
		}

		if("srcTab" in msg){
			handleMessage.data.srcTab = msg.srcTab;
		}

		if("onClickDataExt" in msg){
			handleMessage.data.onClickDataExt = msg.onClickDataExt;
		}

		if("pageReport" in msg){//来自share.php的页面情况报告
			handleMessage.isLoggedIn = msg.pageReport.isLogin;
			handleMessage.hasVideo =  msg.pageReport.hasVideo;
			handleMessage.hasPic =  msg.pageReport.hasPic;			
			handleMessage.executeOnce(resizeWindow,true);//点大按钮时忽略,更新窗口位置
			if(resizeWindow.executed){//执行过一次不在更新窗口位置,来自大按钮的操作
				resizeWindow(false);
			}
		}

		if("notification" in msg){
			//console.log(msg.notification);
			if(msg.notification == "startPostData"){//不返回成功，也不返回失败，30秒后强制关闭转播窗口
				chrome.tabs.getCurrent(function(tab){
					setTimeout(function(){
						chrome.tabs.remove(tab.id);					
					},30*1000);
				});
			}else if(msg.notification == "messageSuccess" || msg.notification == "messageFailed"){//转播按钮点击
				chrome.tabs.getCurrent(function(tab){
					setTimeout(function(){
						chrome.tabs.remove(tab.id);					
					},3500);
				});
			}else if(msg.notification == "startLogin"){
				setTimeout(function(){
					loadFrame(handleMessage.queryurl);
				},1000);
			}
		}

		//console.log("data ready?"+handleMessage.isReady());
		if(handleMessage.isReady()){
			handleMessage.executeOnce(handleMessage.process);
		}
	};

	handleMessage.data = {};
	handleMessage.executeOnce = function( func ){
		if(!!!func.executed){
			if(arguments.length == 2){
				func(arguments[1]);	
			}else{
				func();
			}
			func.executed  = true;
			return;
		}
		//console.log("ignore func");
	};

	handleMessage.isReady = function(){
		//return 	!!(this.data.onClickData && this.data.srcTab && this.data.onClickDataExt)
		return 	!!("onClickData" in this.data && "srcTab" in this.data)
	};

	handleMessage.process = function( data ){
		//console.log("execute funcs");
		var data = data || handleMessage.data;
		var infodata = data.onClickData,
			infodataext = data.onClickDataExt,
			srctab = data.srcTab;
		
		var url,title;
		url = infodata.frameUrl || infodata.pageUrl || srctab.url;
		if(infodataext){//有可能有这个字段，如果有就优先用它
			title = infodataext.title;
		}else{
			title = srctab.title;
		}
		//选择模板
		//默认使用页面模板
		var hasSelectionText = "selectionText" in infodata,
			hasSrc = "srcUrl" in infodata,
			templateChoose = "pageTemplate";//默认使用页面模板

		if(hasSelectionText){
			templateChoose = "textTemplate";
		}

		if(hasSrc){
			templateChoose = "picTemplate";
		}

		//提供模板字段
		//默认页面模板字段,公共字段
		var valmap = {};
		valmap["标题"]= title;
		valmap["网址"]= url;

		if( templateChoose == "textTemplate" ){
			valmap["文字"] = infodata.selectionText;
			valmap["文字链接网址"] = infodata.linkUrl ? infodata.linkUrl:"";
		}else if( templateChoose == "picTemplate" ){
			valmap["图片网址"] = infodata.srcUrl;
			valmap["图片链接网址"] = infodata.linkUrl?infodata.linkUrl:"";
		}

		//渲染模板结果
		//文字内容
		var content = tweetTemplate.renderTemplate( tweetTemplate.getTemplate(templateChoose),valmap );
		var picSrc;

		//图片
		if(hasSrc){
			if(infodata["srcUrl"].endsWith([".jpg",".png",".gif"])){
				picSrc = infodata["srcUrl"]
			}
		}

		//生成Query网址;
		if(picSrc){
			handleMessage.queryurl = buildUrl(content,url,[picSrc]);
		 }else{
			 handleMessage.queryurl = buildUrl(content,url);
		}

		//加载网页
		//console.log("Load Frame");
		//console.log(handleMessage.queryurl);
		loadFrame(handleMessage.queryurl);
	};

	//生成网址
	var buildUrl = function( content,url/*转播视频时用*/,piclist ){
		url = url || "";
		piclist = piclist ? piclist.join("|") : "";
		return ["http://v.t.qq.com/share/share.php"
				,"?"
				,"title="
				,encodeURIComponent(content)
				,"&url="
				,encodeURIComponent(url)
				,"&appkey="
				,"832253e8b2214cea84cc2ecef9098a91"
				,"&pic="
				,piclist
				,"&site="
				,"http://hellohtml5.com"].join("");
	}
	//微博模板
	var tweetTemplate = {};

	tweetTemplate.defaultValues = {//模版默认值
			pageTemplate: "[标题,30][网址]",
			picTemplate:"#分享图片#[图片网址]",
			textTemplate:"[文字]来自[网址]"
	};

	tweetTemplate.getTemplate = function( name ){
		if( name && !empty(name) ){//本地存储无模版
			var storedVal = localStorage[name];
			if(!!storedVal){
				return storedVal;
			}else if(name in tweetTemplate.defaultValues){//有默认数据
				return tweetTemplate.defaultValues[name];
			}
		}
		return "无效微博模版";
	};

	tweetTemplate.renderTemplate = function( template, valMap ){
		return template.replace(/\[(.*?)\]/g,function(regmatch,matched,offset,str){
					var matchedArr = matched.split(",");
					var keystr = matchedArr[0];
					if(keystr in valMap){//要替换的值存在
						var newstr = valMap[keystr];
						if(matchedArr.length > 1){//需要截取
							var maxlen = parseInt(matchedArr[1],10);
							if(newstr.length>maxlen){
								newstr = newstr.substring(0,maxlen)+"...";
								return newstr;
							}
						}
						return newstr;
					}else{//要替换的值不存在,原样返回
						return "["+keystr+"]";
					}
			});
	};
	//根据URL确定窗口大小
	var resizeWindow = function( updateWindowPosition ){
		var windowHeightConfig = {
			loggedin : {
				haspic : 670,
				nopic : 520,
				hasvideo : 630
			},
			nologin : {
				haspic : 860,
				nopic : 740,
				hasvideo : 780
			}
		}

		/*是否登录，是否有图片，是否有视频判定*/
		var haspic = "hasPic" in handleMessage && handleMessage.hasPic;
		var hasvideo = "hasVideo" in handleMessage && handleMessage.hasVideo;
		var loginstatus = "loggedin";//默认为已登录		
		if("isLoggedIn" in handleMessage){//有数据
			loginstatus = handleMessage.isLoggedIn?"loggedin":"nologin";
		}
		
		chrome.windows.getCurrent(function(window){
				var windowSelection = windowHeightConfig[loginstatus];
				var finalHeight;			
				if(haspic && hasvideo){//有图片有视频
					finalHeight = windowSelection["haspic"];
				}else if(haspic && !hasvideo){//有图片无视频
					finalHeight = windowSelection["haspic"];
				}else if(!haspic && hasvideo){//无图片有视频
					finalHeight = windowSelection["hasvideo"];
				}else if(!haspic && !hasvideo){//无图片无视频
					finalHeight = windowSelection["nopic"];
				}
				if(updateWindowPosition){
					var finaltop = Math.max(0,(screen.height - finalHeight)/2);
					chrome.windows.update(window.id,{height:finalHeight,top:finaltop});
				}else{
					chrome.windows.update(window.id,{height:finalHeight,top:finaltop});				
				}
				document.getElementById("contentWrapper").style.height = (finalHeight - 200) + "px";
		});
	}
	//大按钮动作
	var performAction = function( actionname ){
		//console.log(actionname);
		switch(actionname){
			case "deltext":
				if("queryurl" in handleMessage){
					handleMessage.queryurl = handleMessage.queryurl.replace(/title=(.*?)&/,"title=&");
					loadFrame(handleMessage.queryurl);
				}
			break;
			case "delpic":
				if("queryurl" in handleMessage){
					handleMessage.queryurl = handleMessage.queryurl.replace(/pic=(.*?)&/,"pic=&");
					loadFrame(handleMessage.queryurl);
				}
			break;
			case "delvideo":
				if("queryurl" in handleMessage){
					handleMessage.queryurl = handleMessage.queryurl.replace(/url=(.*?)&/,"url=&");
					loadFrame(handleMessage.queryurl);
				}
			break;
            case "emotes":
            	if(emotesListCtrl.isVisible){
			        emotesListCtrl.hide();
	        	}else{
			        emotesListCtrl.show();
		        }
            break;
			case "restore":
				handleMessage.process();
			break;
			default:
				chrome.tabs.getCurrent(function( currenttab ){
					var port = chrome.tabs.connect(currenttab.id,{name:"quickshareaction"});
					port.postMessage({buttonaction:actionname});
					port.disconnect();
				});
		}
	};
	//表情动作
	var performEmote = function( emotename ){
				chrome.tabs.getCurrent(function( currenttab ){
					var port = chrome.tabs.connect(currenttab.id,{name:"quickshareaction"});
					port.postMessage({emoteaction:emotename});
					port.disconnect();
				});
	};
},false);
